﻿using System;
using System.IO;
using System.Text;

namespace Narwhunderful.Aphelia.Framework.IO.Serialization.Binary
{

    public sealed class BurstBinaryReader : IBinaryReader
    {
        private readonly Encoding _encoding;
        private readonly ITypeNameConverter _typeNameConverter;
        private BinaryReader _reader;

        public BurstBinaryReader(ITypeNameConverter typeNameConverter, Encoding encoding)
        {
            if (typeNameConverter == null) throw new ArgumentNullException("typeNameConverter");
            if (encoding == null) throw new ArgumentNullException("encoding");
            _typeNameConverter = typeNameConverter;
            _encoding = encoding;
        }

        public string ReadName()
        {
            return BinaryReaderHelpers.ReadString(_reader);
        }

        public byte ReadElementId()
        {
            return _reader.ReadByte();
        }

        public Type ReadType()
        {
            if (!_reader.ReadBoolean()) return null;
            string typeAsName = _reader.ReadString();
            return _typeNameConverter.ConvertToType(typeAsName);
        }

        public int ReadNumber()
        {
            return BinaryReaderHelpers.ReadNumber(_reader);
        }


        public int[] ReadNumbers()
        {
            return BinaryReaderHelpers.ReadNumbers(_reader);
        }

        public object ReadValue(Type expectedType)
        {
            return BinaryReaderHelpers.ReadValue(expectedType, _reader);
        }

        public void Open(Stream stream)
        {
            _reader = new BinaryReader(stream, _encoding);
        }

        public void Close()
        {
            // don't close the stream if you want to read it further
            //_reader.Close();
        }

    }
}
